﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Identity_MVC.Models;
using Microsoft.Extensions.DependencyInjection;


namespace Identity_MVC.Data
{
    public class ApplicationDbContextSeed
    {


        private UserManager<ApplicationUser> _userManager;

        /// <summary>
        /// 种子数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="service">依赖注入的提供程序</param>
        /// <returns></returns>
        public async Task SeedAsync(ApplicationDbContext context, IServiceProvider service)
        {

            //查找是否有用户


            if (!context.Users.Any())
            {
                //从容器中单独创建一个UserManager<ApplicationUser>的对象
                _userManager = service.GetRequiredService<UserManager<ApplicationUser>>();

                var defaultUser = new ApplicationUser()
                {
                    UserName = "Administrator@qq.com",
                    Email = "Administrator@qq.com",
                    NormalizedUserName = "admin",
                };

                IdentityResult result = await _userManager.CreateAsync(defaultUser, "123456");

                if (!result.Succeeded)
                {
                    throw new Exception("初始化默认用户失败!");
                }

            }

            //using (var scope = service.CreateScope())
            //{




            //}

        }
    }
}
